<template>
	<view v-if="isLoading" style="height: 100vh; background-color: white;"></view>
	<view v-else class="pay-container">
		<nav-bar></nav-bar>
		<view class="pay-header">
			<view class="pay-title">支付确认</view>
			<view class="pay-amount">¥{{ payAmount }}</view>
		</view>
		<view class="pay-info">
			<view class="info-item">
				<text class="label">订单类型</text>
				<text class="value">{{ orderTypeText }}</text>
			</view>
			<view class="info-item" v-if="orderDesc">
				<text class="label">订单描述</text>
				<text class="value">{{ orderDesc }}</text>
			</view>
		</view>
		<view class="pay-methods">
			<view class="method-title">支付方式</view>
			<view class="method-item active">
				<image src="/static/icon/wechat-pay.png" mode="aspectFit" class="method-icon"></image>
				<text class="method-name">微信支付</text>
				<text class="selected-icon">✓</text>
			</view>
		</view>
		<view class="pay-attention-to" v-if="isIos">
			<text>因iOS系统兼容性问题，可能会有支付失败的情况，支付前需要点击右上角“···”，选择刷新</text>
		</view>
		<view class="pay-button" @tap="processPayment">
			<text>确认支付</text>
		</view>
		<view class="cancel-button" @tap="cancelPayment">
			<text>取消</text>
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'

export default {
		components: {
			NavBar
		},
		data() {
			return {
				isIos: false,
				isLoading: true,
				isIOSWechat: false,
				payAmount: '0.00', // 支付金额
				orderType: 0, // 订单类型1会员卡购买2会员卡充值3预约订单4技师物料订单
				orderDesc: '', // 订单描述
				payData: null, // 支付数据
				callbackUrl: '', // 支付完成后的回调页面
				paymentParams: null, // 支付参数
				isSubmitting: false, // 是否正在提交
				sourcePageData: null // 来源页面的数据
			}
		},
		computed: {
			orderTypeText() {
				const typeMap = {
					1: '商品订单',
					2: '会员卡充值',
					3: '服务预约',
					4: '物资订单'
				}
				return typeMap[this.orderType] || '订单支付'
			}
		},
		onLoad(options) {
			this.isIos = uni.getSystemInfoSync().platform === 'ios'
			// 处理ios支付异常问题
			if (options.login === null || options.login === '' || options.login === undefined) {
				uni.navigateTo({
					url: '/pages/login/customer-login'
				})
				this.isLoading = false
				return
			}
			try {
				if (options.code) {
					this.editUserOpenid(options.code)
				}
				const paymentData = uni.getStorageSync('paymentData')
				if (paymentData) {
					this.payAmount = paymentData.payAmount || paymentData.amount || '0.00'
					this.orderType = paymentData.orderType || 0
					this.orderDesc = paymentData.orderDesc || ''
					this.callbackUrl = paymentData.callbackUrl || ''
					this.paymentParams = paymentData.paymentParams || null
					this.sourcePageData = paymentData.sourcePageData || null
					// 检查是否有支付参数，如果有，直接调用支付
					if (this.paymentParams.prepayId) {
						this.payData = this.paymentParams
						// 检查是否有prepayId等直接支付参数
						if ((this.orderType === 3 || this.orderType === 4) &&
							this.paymentParams.prepayId &&
							this.paymentParams.package &&
							this.paymentParams.timeStamp &&
							this.paymentParams.nonceStr &&
							this.paymentParams.paySign) {
							// 构建直接支付所需参数
							const directPayParams = {
								appId: uni.$config.wxAppId,
								timeStamp: this.paymentParams.timeStamp,
								nonceStr: this.paymentParams.nonceStr,
								package: this.paymentParams.package,
								signType: this.paymentParams.signType || 'RSA',
								paySign: this.paymentParams.paySign
							}
							// 延迟一点调用支付，确保页面已完全加载
							setTimeout(() => {
								this.callWechatPay(directPayParams)
							}, 300)
						}
					}
				}
			} catch (e) {
				uni.showModal({
					title: '支付参数错误',
					content: '解析支付参数时发生错误，请返回重试',
					showCancel: false,
					success: () => {
						uni.navigateBack()
					}
				})
			} finally {
				this.isLoading = false
			}
		},
		methods: {
			editUserOpenid(code) {
				let userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}
				uni.request({
					url: `${uni.$config.baseUrl}/wx/wx-service/getOauth2AccessToken`,
					method: 'GET',
					data: {
						code
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							uni.request({
								url: `${uni.$config.baseUrl}/member/member/edit-open-id`,
								method: 'POST',
								data: {
									id: userInfo.memberId,
									openId: res.data.data.openid
								},
								success: (wxRes) => {
									if (wxRes.statusCode === 200 && wxRes.data.code === 200) {
										userInfo.openId = wxRes.data.data.openid
										uni.setStorageSync('userInfo', userInfo)
									}
								}
							})
						}
					}
				})
			},
			processPayment() {
				if (!uni.getStorageSync('paymentData')) {
					uni.showModal({
						title: '支付参数错误',
						content: '未找到支付参数，请返回重试',
						showCancel: false,
						success: () => {
							uni.navigateBack()
						}
					})
				}
				if (this.isSubmitting) {
					uni.showToast({
						title: '处理中，请稍候',
						icon: 'none'
					})
					return
				}
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo.openId) {
					uni.showModal({
						title: '微信授权提示',
						content: '首次支付需要绑定微信账号，是否立即前往授权？',
						confirmText: '去授权',
						cancelText: '取消',
						success: res => {
							if (res.confirm) {
								const currentUrl = encodeURIComponent(window.location.href);
								const appId = uni.$config.wxAppId;
								const redirectUrl =
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
								window.location.href = redirectUrl;
							}
						},
						fail: (err) => {
							uni.showToast({
								title: JSON.stringify(err),
								icon: 'none',
								duration: 2000
							});
						},
					});
					return
				}
				this.isSubmitting = true
				uni.showLoading({
					title: '请求支付中...'
				})
				try {
					if (!userInfo || !userInfo.memberId) {
						uni.hideLoading()
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						this.isSubmitting = false
						return
					}
					// 确保支付参数完整
					if (!this.paymentParams) {
						uni.hideLoading()
						uni.showToast({
							title: '支付参数错误',
							icon: 'none'
						})
						this.isSubmitting = false
						return
					}
					// 构建支付请求参数
					const requestParams = {
						...this.paymentParams,
						memberId: userInfo.memberId,
						paymentMethod: 1, // 微信支付
						orderSource: 1 // H5来源
					}
					// 创建微信支付订单
					uni.request({
						url: (this.orderType === 1 || this.orderType === 2) ?
							`${uni.$config.baseUrl}${this.getApiUrlByOrderType()}` :
							`${uni.$config.baseUrl}${this.getApiUrlByOrderType()}/${this.paymentParams.orderId}`,
						method: 'POST',
						data: requestParams,
						success: (res) => {
							uni.hideLoading()
							if (res.statusCode === 200 && res.data.code === 200 && res.data.data) {
								this.callWechatPay(res.data.data)
							} else {
								uni.showToast({
									title: res.data.msg || '支付请求失败',
									icon: 'none'
								})
								this.isSubmitting = false
							}
						},
						fail: (err) => {
							uni.hideLoading()
							console.error('请求支付失败:', err)
							uni.showToast({
								title: '网络请求失败',
								icon: 'none'
							})
							this.isSubmitting = false
						}
					})
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: '支付处理异常',
						icon: 'none'
					})
					this.isSubmitting = false
				}
			},
			// 根据订单类型获取API URL
			getApiUrlByOrderType() {
				switch (this.orderType) {
					case 1: // 会员卡购买
					case 2: // 会员卡充值
						return '/cardpurchase/cardpurchase/pay'
					case 3: // 预约订单支付调起
						return '/orders/orders/createWxPayOrder'
					case 4: // 物料订单支付调起
						return '/supplieOrder/supplieOrder/createWxPayOrder'
					default:
						return '/orders/orders/createWxPayOrder'
				}
			},
			// 调用微信支付
			callWechatPay(payData) {
				try {
					// 检查必要参数
					if (!payData) {
						throw new Error('支付数据为空')
					}
					if (!payData.appId || !payData.timeStamp || !payData.nonceStr || !payData.package || !payData
						.paySign) {
						uni.showToast({
							title: '支付参数不完整',
							icon: 'none'
						})
						this.isSubmitting = false
						return
					}
					// #ifdef MP-WEIXIN
					// 小程序支付
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payData.timeStamp,
						nonceStr: payData.nonceStr,
						package: payData.package,
						signType: payData.signType || 'RSA',
						paySign: payData.paySign,
						success: () => {
							this.handlePaymentSuccess()
						},
						fail: (err) => {
							uni.showToast({
								title: err.errMsg === 'requestPayment:fail cancel' ? '支付取消' : '支付失败',
								icon: 'none'
							})
							this.handlePaymentFailure()
						},
						complete: () => {
							this.isSubmitting = false
						}
					})
					// #endif
					// #ifdef H5
					// H5支付
					const isWechatBrowser = /MicroMessenger/i.test(navigator.userAgent)
					if (isWechatBrowser) {
						if (typeof WeixinJSBridge === 'undefined') {
							document.addEventListener('WeixinJSBridgeReady', () => {
								this.onWeixinJSBridgeReady(payData)
							}, false)
							uni.showToast({
								title: '请在微信内完成支付',
								icon: 'none'
							})
						} else {
							this.onWeixinJSBridgeReady(payData)
						}
					} else {
						uni.showModal({
							title: '支付提示',
							content: '请在微信浏览器中打开进行支付',
							showCancel: false,
							success: () => {
								this.isSubmitting = false
								this.navigateBack()
							}
						})
					}
					// #endif
				} catch (e) {
					console.error('调用支付过程中发生错误:', e)
					uni.showToast({
						title: '支付调用异常',
						icon: 'none'
					})
					this.isSubmitting = false
				}
			},
			// WeixinJSBridge回调处理
			onWeixinJSBridgeReady(payData) {
				try {
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							"appId": uni.$config.wxAppId,
							"timeStamp": payData.timeStamp,
							"nonceStr": payData.nonceStr,
							"package": payData.package,
							"signType": payData.signType || "RSA",
							"paySign": payData.paySign
						},
						(res) => {
							if (res.err_msg === "get_brand_wcpay_request:ok") {
								// 支付成功
								this.handlePaymentSuccess()
							} else if (res.err_msg === "get_brand_wcpay_request:cancel") {
								// 用户取消支付
								uni.showToast({
									title: '支付已取消',
									icon: 'none'
								})
								this.handlePaymentFailure()
							} else {
								// 支付失败
								uni.showToast({
									title: '支付失败: ' + res.err_msg,
									icon: 'none'
								})
								console.error('微信支付失败:', res.err_msg)
								this.handlePaymentFailure()
							}
							this.isSubmitting = false
						}
					)
				} catch (e) {
					console.error('WeixinJSBridge调用出错:', e)
					uni.showToast({
						title: '支付接口调用失败',
						icon: 'none'
					})
					this.isSubmitting = false
				}
			},
			// 处理支付成功
			handlePaymentSuccess() {
				if (this.paymentParams.orderType !== 1) {
					this.updateOrderPaymentStatus(this.paymentParams.orderId, 1)
				}
				uni.showToast({
					title: '支付成功',
					icon: 'success',
					duration: 2000,
					success: () => {
						setTimeout(() => {
							// 创建支付结果对象
							const paymentResult = {
								success: true,
								sourcePageData: this.sourcePageData
							}
							// 使用缓存存储支付结果
							uni.setStorageSync('paymentResult', paymentResult)
							// 清除支付参数缓存
							uni.removeStorageSync('paymentData')
							// 如果是次卡充值且有附赠项目，添加附赠项目
							if (this.sourcePageData && this.sourcePageData.times && this.sourcePageData
								.projectId && this.sourcePageData.giftTimes) {
								this.addGiftProject()
							} else {
								// 没有附赠项目，直接跳转
								this.navigateAfterPayment()
							}
						}, 1500)
					}
				})
			},

			// 更新订单支付状态
			updateOrderPaymentStatus(orderId, paymentStatus) {
				if (!orderId) {
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/orders/orders/updatePaymentStatus`,
					method: 'POST',
					data: {
						orderId: orderId,
						paymentStatus: paymentStatus
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							console.log('订单支付状态更新成功')
						} else {
							console.error('订单支付状态更新失败:', res.data.message || '未知错误')
						}
					},
					fail: (err) => {
						console.error('更新订单支付状态请求失败:', err)
					}
				})
			},
			// 添加附赠项目
			addGiftProject() {
				// 获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				try {
					if (userInfoStr) {
						if (typeof userInfoStr === 'string') {
							try {
								const parsed = JSON.parse(userInfoStr)
								if (parsed.code === 200 && parsed.data) {
									userInfo = parsed.data
								} else {
									userInfo = parsed
								}
							} catch (e) {
								userInfo = userInfoStr
							}
						} else {
							userInfo = userInfoStr
						}
					}
					if (!userInfo || !userInfo.memberId) {
						this.navigateAfterPayment()
						return
					}
					// 构建请求参数
					const requestData = {
						memberId: userInfo.memberId,
						cardId: this.sourcePageData.cardId,
						projectId: this.sourcePageData.projectId,
						times: this.sourcePageData.giftTimes,
						projectName: this.sourcePageData.projectName
					}
					// 发送请求添加附赠项目
					uni.request({
						url: `${uni.$config.baseUrl}/cardgiftuser/cardgiftuser/add`,
						method: 'POST',
						data: requestData,
						success: (res) => {
							if (res.data.code === 200) {} else {}
						},
						fail: (err) => {},
						complete: () => {
							this.navigateAfterPayment()
						}
					})
				} catch (e) {
					this.navigateAfterPayment()
				}
			},
			// 支付完成后跳转
			navigateAfterPayment() {
				// 如果有回调URL，跳转到回调页面
				if (this.callbackUrl) {
					// 判断是否使用switchTab
					if (this.callbackUrl.startsWith('/pages/index/') || this.callbackUrl.startsWith('/pages/my/') || this
						.callbackUrl.startsWith('/pages/category/')) {
						uni.switchTab({
							url: this.callbackUrl
						})
					} else {
						uni.redirectTo({
							url: `${this.callbackUrl}&paymentResult=success`
						})
					}
				} else {
					// 没有回调URL，返回上一页
					uni.navigateBack()
				}
			},
			// 处理支付失败或取消
			handlePaymentFailure() {
				setTimeout(() => {
					// 创建支付结果对象
					const paymentResult = {
						success: false,
						sourcePageData: this.sourcePageData
					}
					// 使用缓存存储支付结果
					uni.setStorageSync('paymentResult', paymentResult)
					// 清除支付参数缓存
					uni.removeStorageSync('paymentData')
					this.navigateBack(false)
				}, 1500)
			},
			// 取消支付
			cancelPayment() {
				uni.showModal({
					title: '取消支付',
					content: '确定要取消此次支付吗？',
					success: (res) => {
						if (res.confirm) {
							this.navigateBack(false)
						}
					}
				})
			},
			// 返回上一页
			navigateBack(success = false) {
				// 创建支付结果对象
				const paymentResult = {
					success: success,
					sourcePageData: this.sourcePageData
				}

				// 使用缓存存储支付结果
				uni.setStorageSync('paymentResult', paymentResult)

				// 如果有回调URL，跳转到回调页面
				if (this.callbackUrl) {
					// 判断是否使用switchTab
					if (this.callbackUrl.startsWith('/pages/index/') ||
						this.callbackUrl.startsWith('/pages/my/') ||
						this.callbackUrl.startsWith('/pages/category/')) {
						uni.switchTab({
							url: this.callbackUrl
						})
					} else {
						uni.redirectTo({
							url: `${this.callbackUrl}?paymentResult=${success ? 'success' : 'fail'}`
						})
					}
				} else {
					// 没有回调URL，返回上一页
					uni.navigateBack()
				}
			}
		}
	}
</script>

<style lang="scss">
	.pay-attention-to {
		background-color: #FFFFFF;
		color: #ff0000;
		font-size: 80%;
	}

	.pay-container {
		min-height: 100vh;
		background-color: #f7f7f7;
		padding: 30rpx;

		.pay-header {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 40rpx 30rpx;
			margin-bottom: 30rpx;
			text-align: center;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.pay-title {
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
			}

			.pay-amount {
				font-size: 64rpx;
				font-weight: bold;
				color: #333333;
			}
		}

		.pay-info {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.info-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					font-size: 28rpx;
					color: #666666;
				}

				.value {
					font-size: 28rpx;
					color: #333333;
					font-weight: 500;
				}
			}
		}

		.pay-methods {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 40rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			.method-title {
				font-size: 30rpx;
				color: #333333;
				margin-bottom: 30rpx;
			}

			.method-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;

				&.active {
					.method-name {
						color: #07C160;
					}
				}

				.method-icon {
					width: 48rpx;
					height: 48rpx;
					margin-right: 20rpx;
				}

				.method-name {
					flex: 1;
					font-size: 28rpx;
					color: #333333;
				}

				.selected-icon {
					font-size: 28rpx;
					color: #07C160;
				}
			}
		}

		.pay-button {
			background: #07C160;
			border-radius: 16rpx;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;

			text {
				font-size: 32rpx;
				color: #FFFFFF;
				font-weight: 500;
			}

			&:active {
				opacity: 0.9;
			}
		}

		.cancel-button {
			border-radius: 16rpx;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 1rpx solid #D1D1D1;

			text {
				font-size: 32rpx;
				color: #666666;
			}

			&:active {
				background: #F5F5F5;
			}
		}
	}
</style>